package com.ysh.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/*
    处理统一字符集过滤器
 */
public class EncodingFilter implements Filter {
    private String encoding = null;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 获取初始化参数
        encoding = filterConfig.getInitParameter("encodingCharacter");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 类型转换
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        // 统一编码
        request.setCharacterEncoding(encoding);
        response.setContentType("text/html;charset="+encoding);

        // 放行
        filterChain.doFilter(request,response);


    }

    @Override
    public void destroy() {

    }
}
